<?php
namespace App\Handlers;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class ImageUploadHandler{
    //允许上传的图片格式
    protected $allowed_ext = ['jpg','png','gif','jpeg'];

    //保存图片的方法，最终返回一个图片所在的url地址
    public function save($file,$folder,$model_id,$max_width=false,$unlink=false){
        //文件夹
        $folder_name = "uploads/images/{$folder}/".date('Ym/d',time());
        //文件夹的物理地址
        $upload_path = public_path().'/'.$folder_name;
        //获取文件后缀
        $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';
        //获取唯一文件名
        $filename = md5($model_id.time()).'.'.$extension;
        //判断是不是图片
        if(!in_array($extension,$this->allowed_ext)){
            return false;
        }
        //将图片从临时保存区移动到指定位置，并重新命名
        $file->move($upload_path,$filename);
        //缩放图片
        if($max_width && $extension != 'gif'){
            $this->reduceSize($upload_path.'/'.$filename,$max_width);
        }
        if($unlink){
            $this->delOldImage($model_id);
        }
        return [
            'path'=> config('app.url')."/$folder_name/$filename"
        ];
    }
    //缩放裁切图片
    public function reduceSize($file_path,$max_width){
        //实例化
        $image = Image::make($file_path);
        //缩放
        $image->resize($max_width,null,function($obj){
            //等比例缩放
           $obj->aspectRatio();
           //防止放大
            $obj->upsize();
        });
        $image->save();
    }

    public function delOldImage($user_id){
        $user = DB::table('users')->find($user_id);
        if($user){
            $user_avatar = $user->avatar;
            $pic_arr = explode('/',$user_avatar);
            $slice_arr = array_slice($pic_arr,3,5);
            $public_path = implode('/',$slice_arr);
            //获取文件名
            $old_file_name = array_pop($pic_arr);
            //物理地址
            $old_upload_file_path = public_path()."/$public_path/$old_file_name";
            @unlink($old_upload_file_path);
        }
    }

}
